package com.learn.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.learn.pojo.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/03/19
 * @description 自定义yaml消息转换器
 */
public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter {
    private ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));

    // 还有一个很重要的步骤是在创建类时，指定媒体类型
    public MyYamlHttpMessageConverter() {
        super(new MediaType("text", "yaml", StandardCharsets.UTF_8));
    }

    // 表示哪个类支持该消息转换器
    @Override
    protected boolean supports(Class clazz) {
        // 判断clazz是否继承自User
        return User.class.isAssignableFrom(clazz);
    }

    // 请求时的消息转换，将前端yaml数据转为java对象
    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    // 响应时的消息转换，将java对象转为yaml数据
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // getBody获取输出流
        objectMapper.writeValue(outputMessage.getBody(), o);
    }
}
